package com.cx.util.device;

import android.util.Pair;
import android.view.View;

import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.cx.util.Preconditions;


public class FragmentHelper {


    public static void replace(int resId, Fragment fragment,
                               FragmentManager manager, Pair<View, String>... sharedElements) {
        replace(resId, fragment, manager, false,sharedElements);
    }

    public static void replace(int resId,
                               Fragment fragment,
                               FragmentManager manager,
                               boolean addToBackStack,
                               Pair<View, String>... sharedElements) {
        Preconditions.checkNotNull(manager);
        Preconditions.checkNotNull(fragment);
        FragmentTransaction transaction = manager.beginTransaction();
        if (sharedElements != null) {
            for (Pair<View, String> pair : sharedElements) {
                transaction.addSharedElement(pair.first, pair.second);
            }
        }

        Fragment fragmentByTag = manager.findFragmentByTag(fragment.getClass().getName());
        if (fragmentByTag != null)
            manager.popBackStack();

        transaction.replace(resId, fragment, fragment.getClass().getName());
        if (addToBackStack)
            transaction.addToBackStack(null);
        transaction.commitNowAllowingStateLoss();
    }

    public static void showDialog(DialogFragment fragment, FragmentManager manager) {
        String name = fragment.getClass().getName();
        showDialog(fragment,name,manager);

    }


    public static void showDialog(DialogFragment fragment, String name, FragmentManager manager) {

        Fragment fragmentByTag = manager.findFragmentByTag(name);
        if (fragmentByTag != null)
            manager.beginTransaction().remove(fragmentByTag).commitNowAllowingStateLoss();

        if (!fragment.isAdded()) {
            FragmentTransaction transaction = manager.beginTransaction();
            transaction.add(fragment, name);
            transaction.commitNowAllowingStateLoss();
        }

    }

}
